package com.canyou.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.canyou.system.entity.menu.MenuDetailVO;
import com.canyou.system.entity.menu.MenuListVO;
import com.canyou.system.mapper.MenuMapper;
import com.canyou.system.model.Menu;
import com.canyou.system.service.MenuService;
import com.canyou.utils.TreeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author canyou
 * @since 2019-05-14
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Override
    public boolean removeById(Long menuId) {
        return baseMapper.deleteById(menuId) > 0;
    }

    @Override
    public List<Menu> getMenuListByUserId(Long userId) {
        return baseMapper.getMenuListByUserId(userId);
    }

    @Override
    public List<MenuListVO> getMenuTree(Integer type) {
        List<MenuListVO> list = baseMapper.getMenuListByType(type);
        return TreeUtils.build(list, 0L);
    }

    @Override
    public MenuDetailVO getDetailById(Long id) {
        Menu menu = baseMapper.selectById(id);
        Menu parentMenu = baseMapper.selectById(menu.getParentId());
        MenuDetailVO menuDetailVO = new MenuDetailVO();
        BeanUtils.copyProperties(menu, menuDetailVO);
        if (parentMenu != null) {
            menuDetailVO.setParentName(parentMenu.getTitle());
        }
        return menuDetailVO;
    }

    @Override
    public boolean existMenu(String permission, Long menuId) {
        LambdaQueryWrapper<Menu> queryWrapper = Wrappers.<Menu>lambdaQuery().eq(Menu::getPermission, permission);
        if (menuId != null) {
            queryWrapper.ne(Menu::getId, menuId);
        }
        return baseMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public int getMenuRoleCount(Long menuId) {
        return baseMapper.getMenuRoleCount(menuId);
    }

}
